package com.epower.base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.epower.bo.epower.commons.Constants;
import com.epower.bo.epoweruser.EpowerUserService;
import com.epower.dataobject.EpowerUserDO;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("unchecked")
public class BaseAction extends ActionSupport implements SessionAware {
	private static final long serialVersionUID = 7832295150101890553L;
	protected Map session;

	public void setSession(Map session) {
		this.session = session;
	}

	public ArrayList<Object> pages;
	private EpowerUserService epowerUserBO;

	/**
	 * 详细页码 如 1..34567..100
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */
	public ArrayList<Object> getPagesList(int nowPage, int totalPage) {
		if (nowPage > totalPage)
			nowPage = totalPage;

		int index = 1;
		ArrayList<Object> al = new ArrayList<Object>();
		al.add(index);
		index++;
		int from = 0;
		if (nowPage > 5 && nowPage <= totalPage - 1) {
			al.add("0");
			index++;
			from = nowPage - 2;
		} else
			from = 2;

		for (index = from; index < from + 5; index++) {
			if (index <= totalPage)
				al.add(index);
		}

		if (index < totalPage)
			al.add("0");

		if (index <= totalPage)
			al.add(totalPage);

		return al;
	}

	public EpowerUserDO getUser() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		String userName = (String) session.getAttribute(Constants.USER_NAME);
		// 正常情况不会出现
		if (userName == null) {
			HttpServletRequest request = ServletActionContext.getRequest();

			Cookie allCookie[] = request.getCookies();
			if (allCookie != null) {
				for (Cookie cookie : allCookie) {
					if (Constants.USER_NAME.equals(cookie.getName())) {
						userName = cookie.getValue();
						// 存入Session
						session.setAttribute(Constants.USER_NAME, cookie.getValue());
						break;
					}

				}
			}
		}
		return epowerUserBO.getUserByUserName(userName);
	}

	public ArrayList<Object> getPages() {
		return pages;
	}

	public void setPages(ArrayList<Object> pages) {
		this.pages = pages;
	}

	public void write(String content) throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(content);
	}

	public void setEpowerUserBO(EpowerUserService epowerUserBO) {
		this.epowerUserBO = epowerUserBO;
	}

}
